home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Language/OS - Multiplatform Resource Library
/
LANGUAGE OS.iso
/
cpp_libs
/
answrbok
/
8_3.lha
/
8_3
/
8_3_int.c
< prev
next >
Wrap
C/C++ Source or Header
|
1993-08-08
|
835b
|
43 lines
* Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
* The C++ Answer Book */
* Tony Hansen */
* All rights reserved. */
/ Exercise 8.3
/ Read in an integer, with error checking
include <stream.h>
include <errno.h>
include <stdlib.h>
nt read_integer(ostream &out, istream &in, long *val)
// set up flushing of the output stream
ostream *old = in.tie(&out);
// loop until we get something right
for ( ; ; out << "Try again\n")
{
out << "Type an integer: ";
// read a line, including the newline
char buf[256], c;
if (!cin.get(buf, 256))
{
in.tie(old);
return 0;
}
in.get(c);
// check the integer
char *p;
errno = 0;
long ret = strtol(buf, &p, 10);
if (*p || (p == buf) || errno)
continue;
// return the value, restoring the old tie first
in.tie(old);
*val = ret;
return 1;
}